/**
 * Created by Alice on 2016/9/9 0009
 */

var flag = utils.get_url_param("flag");
var s;
$(function () {
    init_top();
    // init_data();
    layui.use('layer', function () {
        layer = layui.layer;
    });
});

function init_top() {
    $("#sys_fault_condition").find("a").attr("href", r.base_path + "views/system_monitor/sys_fault_condition.html?court=" + r.court_id);
    $("#sys_play_info").find("a").attr("href", r.base_path + "system_monitor/sys_play_info?courtUid=" + r.court_uid);
    $("#sys_meeting").find("a").attr("href", r.base_path + "views/system_monitor/sys_meeting.html?court=" + r.court_id);
    $("#sys_server_status").find("a").attr("href", r.base_path + "system_monitor/sys_server_status?courtUid=" + r.court_uid);
    $("#sys_warning_message").find("a").attr("href", r.base_path + "system_monitor/sys_warning_message?courtUid=" + r.court_uid);
    $("#sys_equipment_management").find("a").attr("href", r.base_path + "views/system_monitor/sys_equipment_management.html?court=" + r.court_id);
    $("#sys_log_info").find("a").attr("href", r.base_path + "system_monitor/sys_log_info?courtUid=" + r.court_uid);
    if (flag == 2) {
        $("#tips").html("科技法庭信息：");
    } else if (flag == 5) {
        $("#tips").html("高清法庭信息：");
    } else if (flag == 4) {
        $("#tips").html("标清法庭信息：");
    } else {
        $("#tips").html("所有法庭信息：");
    }
}

function init_data(data) {
    // var urlPath = "";
    // if (flag == 2) {
    //     urlPath = "GetCourtStatus";
    // } else if (flag == 5) {
    //     urlPath = "GetHighCourtStatus";
    // } else if (flag == 4) {
    //     urlPath = "GetNormCourtStatus";
    // } else {
    //     urlPath = "GetCourtStatus";
    // }
    // $("#loading").hide();
    // $.get(r.base_path + "sys/" + urlPath, {courtId: r.court_id}, function (result) {
    //     if (result && result.status == 0) {
    s = data;
    selectCourtStatus();
    initChart();
    //     } else {
    //         scs_content.html('<span class="context-span more-errmsg">暂无法庭信息。</span>');
    //     }
    // }, 'json').fail(function () {
    //     scs_content.html('<span class="context-span">获取法庭信息失败！</span>');
    // });

}
var html = $("#_court_div");
var scs_content = $("#scs_content");
function selectCourtStatus() {
    scs_content.html("");
    if (s.length == 0) {
        scs_content.html('<span class="more-errmsg">暂无法庭信息</span>');
    }
    $(s).each(function (i, n) {
        var temp = html.clone();
        var _court_ = temp.find("._court_");
        var href = 'javascript:;';
        if (n.planUid) {
            // if (n.third) {
            //     href = r.base_path + "sys/panel_living?uid=" + n.planId + "&cid=" + n.courtroomUid + "&third=third" + "&vc=" + r.court_id+'&court='+r.court_id
            // } else {
            //     href = r.base_path + "views/system_monitor/living.html?uid=" + n.planId + "&cid=" + n.courtroomUid + "&vc=" + r.court_id+'&court='+r.court_id
            href = r.base_path + "system_monitor/panel_living?planUid=" + n.planUid + "&courtRoomUid=" + n.courtroomUid + "&vcCourtUid=" + r.court_uid
            // }
        }
        temp.find(".csc_living").attr("href", href);
        //法庭名
        var _court_ = temp.find("._court_");
        _court_.html(n.courtRoomName);
        _court_.attr('title', n.courtRoomName);
        //开庭信息
        var _court_courtroom = temp.find("._court_courtroom");
        _court_courtroom.html(n.caseName ? n.caseName : n.status);

        temp.find(".csc-status").html(n.status);

        n.status != "空闲" ? _court_courtroom.attr('title', n.caseName) : _court_courtroom.attr('title', '空闲');

        temp.find('.scs-status').empty();
        temp.find('.scs-right').addClass('item_' + n.courtroomUid);
        if (n.cfg) {
            var arr = n.cfg;
            arr.sort(function (a, b) {
                return a.encodeip != b.ip;
            });
            $(arr).each(function (index, m) {
                var status_info = '正在录制';
                var status_class = 'status-badge-success';
                if (!n.planId || m.isrecord != 1 || n.status == '空闲' || n.status == '即将开庭') {
                    status_info = '未启动';
                    status_class = 'status-badge-close';
                }
                var device;
                if (!n.third) {
                    device = $('<div class="scs-device cursor-hand">' +
                        '<div class="scs-device-success white center ' + status_class + '">' + status_info + '</div>' +
                        '<div class="scs-device-content white center">' + m.chnname + '</div>' +
                        '</div>');
                } else {
                    device = $('<div class="scs-device cursor-hand">' +
                        '<div class="scs-device-success white center ' + status_class + '">' + status_info + '</div>' +
                        '<div class="scs-device-content white center">' + m.chnname + '</div>' +
                        '</div>');
                }
                device.click(function () {
                    if (status_info == '未启动') {
                        layer.msg('设备未启动，请开启设备。');
                        return;
                    }
                    window.location.href = r.base_path + "views/system_monitor/living.html?uid=" + n.planId + "&cid=" + n.courtroomUid + (n.third ? "&third=third" : "&channel=" + m.index) + "&vc=" + r.court_id + '&court=' + r.court_id;
                    // console.log(m);
                });
                temp.find('.scs-status').append(device);

            });
        }
        scs_content.append(temp);
        /* $('.item_'+n.courtroomUid).find('.scs-device').click(function () {
         console.log(this);
         console.log($('.item_'+n.courtroomUid).find('.scs-status').index(this));
         })*/
    });
    $('#loading').hide()
}
var setting = {
    getDataInterval: 999999999999999999999999,// 刷新时间间隔 毫秒
    hd: {
        options: {
            series: {
                pie: {
                    innerRadius: 0.5,
                    show: true,
                    combine: {
                        color: '#999',
                        threshold: 0.1
                    }
                }
            },
            grid: {borderWidth: 0, hoverable: true, clickable: true},
            legend: {
                show: false
            }
        },
        series: 2,
        colorArray: ['#ff5b57', '#00acac'],
        nameArray: ['已用', '剩余']
    },
    cpu: {
        options: {
            series: {
                shadowSize: 0	// Drawing is faster without shadows
            },
            colors: ["#99CCFF"],
            yaxis: {
                ticks: 3,
                min: 0,
                max: 100,
                font: {
                    color: ["#99CCFF"]
                },
                tickFormatter: function (val, axis) {
                    return val.toFixed(axis.tickDecimals) + '%';
                }
            },
            xaxis: {
                show: false
            },
            grid: {
                color: ["#99CCFF"],
                borderWidth: 1
            }
        },
        totalPoints: 100, //细度总量
        cpu_0_Data: null,
        cpu_1_Data: null,
        updateInterval: 1000
    },
    ram: {
        options: {
            series: {
                shadowSize: 0	// Drawing is faster without shadows
            },
            colors: ["#99CCFF"],
            yaxis: {
                ticks: 3,
                min: 0,
                max: 100,
                font: {
                    color: ["#99CCFF"]
                },
                tickFormatter: function (val, axis) {
                    return val.toFixed(axis.tickDecimals) + '%';
                }
            },
            xaxis: {
                show: false
            },
            grid: {
                color: ["#99CCFF"],
                borderWidth: 1,
                labelBoxBorderColor: ["#99CCFF"]

            }
        },
        totalPoints: 100, //细度总量
        updateInterval: 1000
    }
};
var initChart = function () {
    function update() {
        $.get(r.base_path + 'device/getDevStatus', {courtUid: r.court_uid}, function (result) {
            //result = {status : 0};
            //result.data = demoJson;
            if (result && result.status == 0) {
                $(result.data).each(function (index, courtroom) {
                    var courtroom_item = $('.item_' + courtroom.uid);
                    var status = courtroom_item.parent().parent().find('.csc-status').html();
                    if (courtroom.videoCaptureStatusProfiles) {
                        courtroom.videoCaptureStatusProfiles.sort(function (a, b) {
                            return a.dspStatus.replace(/[^0-9]/ig, "") - b.dspStatus.replace(/[^0-9]/ig, "")
                        });
                        $(courtroom.videoCaptureStatusProfiles).each(function (video_index, channel) {
                            var channel_div = courtroom_item.find('.scs-device').eq(video_index).find('div').eq(0);
                            var div_class = channel_div.attr('class');
                            // console.log(div_class,div_class.indexOf("status-badge-success"));
                            if (div_class.indexOf("status-badge-success") > -1) {
                                // var reg = channel.dspStatus.replace(/[^0-9]/ig,"");
                                // console.log(reg,channel.resolution);
                                if (channel.resolution == 'NOSINGAL') {
                                    channel_div.attr('class', 'scs-device-success white center status-badge-warning');
                                    channel_div.html('无信号');
                                }
                            }
                        });
                    }
                    if (courtroom_item && status != '空闲') {
                        draw.initHD(courtroom_item, courtroom);
                        draw.initCPU(courtroom_item, courtroom);
                        draw.initRAM(courtroom_item, courtroom);
                    }
                });
            }
            $('#loading').hide();
        }).fail(function () {
            $('#loading').hide();
        });
        //setTimeout(update, setting.getDataInterval);
    }

    var draw = {
        initHD: function (courtroom_item, courtroom) {
            var data = [];
            var dataArray = [];
            var storageTotalSpace;
            var storageRemainingSpace;
            storageTotalSpace = courtroom.storageTotalSpace || courtroom.totalsize;
            storageRemainingSpace = courtroom.storageRemainingSpace || courtroom.freedisk;
            if (!storageTotalSpace) {//无硬盘
                courtroom_item.find('.hd-inner').show();
                courtroom_item.find('.scs-plot-hd-nohd').html('无硬盘');
                return;
            }
            storageTotalSpace = parseInt(storageTotalSpace.replace(/[^0-9]+/g, ''));
            storageRemainingSpace = parseInt(storageRemainingSpace.replace(/[^0-9]+/g, ''));
            dataArray.push(storageTotalSpace - storageRemainingSpace);
            dataArray.push(storageRemainingSpace);
            //构建硬盘饼图
            for (var i = 0; i < setting.hd.series; i++) {
                data[i] = {label: setting.hd.nameArray[i], data: dataArray[i], color: setting.hd.colorArray[i]};
            }
            courtroom_item.find('.hd-inner').show();
            $.plot(courtroom_item.find('.hd-inner').find('.scs-placeholder'), data, setting.hd.options);

        },
        initCPU: function (courtroom_item, courtroom) {
            var cpu_0_Data = new Array(setting.cpu.totalPoints - 1);
            cpu_0_Data.push(0);
            var cpu_1_Data = new Array(setting.cpu.totalPoints - 1);
            cpu_1_Data.push(0);

            function getCpu_0_Data() {
                var y = courtroom.cpu ? parseInt(courtroom.cpu.replace(/[^0-9.]+/g, '')) : 40;
                y = y + Math.random() * 30;

                var r = Math.random() * 100;
                if (r > 99) {//CPU频率有 1%的概率突然飙升 1秒
                    y = y + 50;
                }

                if (y < 0) {
                    y = 0;
                } else if (y > 100) {
                    y = 100;
                }
                if (cpu_0_Data.length >= setting.cpu.totalPoints) {
                    cpu_0_Data = cpu_0_Data.slice(1);
                }
                cpu_0_Data.push(y);
                var res = [];
                for (var i = 0; i < cpu_0_Data.length; ++i) {
                    res.push([i, cpu_0_Data[i]]);
                }
                return res;
            }

            function getCpu_1_Data() {
                var y = courtroom.cpu1 ? parseInt(courtroom.cpu1.replace(/[^0-9.]+/g, '')) : 30;
                y = y + Math.random() * 30;

                var r = Math.random() * 100;
                if (r > 99) {//CPU频率有 1%的概率突然飙升 1秒
                    y = y + 50;
                }

                if (y < 0) {
                    y = 0;
                } else if (y > 100) {
                    y = 100;
                }
                if (cpu_1_Data.length > setting.cpu.totalPoints) {
                    cpu_1_Data = cpu_1_Data.slice(1);
                }
                cpu_1_Data.push(y);
                var res = [];
                for (var i = 0; i < cpu_1_Data.length; ++i) {
                    res.push([i, cpu_1_Data[i]]);
                }
                return res;
            }

            courtroom_item.find('.cpu-inner').show();
            var plot_cpu0 = $.plot(courtroom_item.find('.cpu-0'), [getCpu_0_Data()], setting.cpu.options);
            var plot_cpu1 = $.plot(courtroom_item.find('.cpu-1'), [getCpu_1_Data()], setting.cpu.options);

            function update() {
                plot_cpu0.setData([getCpu_0_Data()]);
                plot_cpu0.draw();
                plot_cpu1.setData([getCpu_1_Data()]);
                plot_cpu1.draw();
                setTimeout(update, setting.cpu.updateInterval);
            }

            update();//调用刷新定时器
        },
        initRAM: function (courtroom_item, courtroom) {
            var ram_0_Data = new Array(setting.ram.totalPoints - 1);
            ram_0_Data.push(0);
            var y = courtroom.mem ? parseInt(courtroom.mem.replace(/[^0-9.]+/g, '')) : 30;

            function getRam_0_Data() {
                var r = Math.random() * 100;
                if (r > 97) {//内存有3%的概率发生突变
                    y = y - 5;
                }
                r = Math.random() * 100;
                if (r > 97) {
                    y = y + 5;
                }

                if (y < 30) {
                    y = 30;
                } else if (y > 80) {
                    y = 80;
                }
                if (ram_0_Data.length >= setting.ram.totalPoints) {
                    ram_0_Data = ram_0_Data.slice(1);
                }
                ram_0_Data.push(y);
                var res = [];
                for (var i = 0; i < ram_0_Data.length; ++i) {
                    res.push([i, ram_0_Data[i]])
                }
                return res;
            }

            courtroom_item.find('.ram-inner').show();
            var plot_ram0 = $.plot(courtroom_item.find('.ram-0'), [getRam_0_Data()], setting.ram.options);

            function update() {
                plot_ram0.setData([getRam_0_Data()]);
                plot_ram0.draw();
                setTimeout(update, setting.ram.updateInterval);
            }

            update();//调用刷新定时器
        }
    };

    update();//调用刷新定时器
};

var demoJson = [
    {
        "serialNumber": "",
        "flashTotalSpace": "0GB",
        "storageRemainingSpace": "1029GB",
        "storageTotalSpace": "2015GB",
        "devip": "192.168.15.88",
        "systemTime": "2017-04-10 17:26:31",
        "baseInfoProfileToken": "baseInfo_1",
        "uid": "34612b0a6e3e40d89a06bdfe63ccb37c",
        "baseStatusProfileToken": "baseInfo_1",
        "courtroomname": "福建高院第七法庭",
        "flashRemainingSpace": "0GB",
        "netAcceptSpeed": "28.76kb/s",
        "netSendSpeed": "0.40kb/s",
        "videoCaptureStatusProfiles": [
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI",
                "dspStatus": "视频采集通道1",
                "resolution": "1080P",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI",
                "dspStatus": "视频采集通道2",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI",
                "dspStatus": "视频采集通道3",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI",
                "dspStatus": "视频采集通道4",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI",
                "dspStatus": "视频采集通道101",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI",
                "dspStatus": "视频采集通道102",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI-I",
                "dspStatus": "视频采集通道103",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI-I",
                "dspStatus": "视频采集通道104",
                "resolution": "NOSINGAL",
                "token": ""
            }
        ],
        "temperature": "0",
        "memoryUtilization": "60.15%",
        "humidity": "0",
        "deviceModel": "EN11_DE2",
        "hardwareVersion": "v3.0",
        "status.cpu": "51.08",
        "softwareVersion": "3.0.5.1",
        "machineType": "10",
        "status.cpu_1": "8.44"
    },
    {
        "serialNumber": "",
        "flashTotalSpace": "10GB",
        "storageRemainingSpace": "0GB",
        "storageTotalSpace": "0GB",
        "devip": "192.168.15.155",
        "systemTime": "2017-04-10 17:27:18",
        "baseInfoProfileToken": "baseInfo_1",
        "uid": "066b03da428848ee8b0b26b946f87f36",
        "baseStatusProfileToken": "baseInfo_1",
        "courtroomname": "福建高院第六法庭",
        "flashRemainingSpace": "0GB",
        "netAcceptSpeed": "28.69kb/s",
        "netSendSpeed": "0.00kb/s",
        "videoCaptureStatusProfiles": [
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道1",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道2",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道3",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道4",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道101",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道102",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI-I",
                "dspStatus": "视频采集通道103",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI-I",
                "dspStatus": "视频采集通道104",
                "resolution": "NOSINGAL",
                "token": ""
            }
        ],
        "temperature": "0",
        "memoryUtilization": "7.49%",
        "humidity": "0",
        "deviceModel": "EN11_DE2",
        "hardwareVersion": "v3.0",
        "status.cpu": "67.84",
        "softwareVersion": "3.0.1.6",
        "machineType": "9",
        "status.cpu_1": "42.46"
    },
    {
        "serialNumber": "",
        "flashTotalSpace": "50GB",
        "storageRemainingSpace": "0GB",
        "storageTotalSpace": "0GB",
        "devip": "192.168.15.155",
        "systemTime": "2017-04-10 17:27:19",
        "baseInfoProfileToken": "baseInfo_1",
        "uid": "391ad6aaeaa1462bba26ed1b6f2bea8d",
        "baseStatusProfileToken": "baseInfo_1",
        "courtroomname": "福建高院第九法庭",
        "flashRemainingSpace": "0GB",
        "netAcceptSpeed": "41.19kb/s",
        "netSendSpeed": "0.40kb/s",
        "videoCaptureStatusProfiles": [
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道1",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道2",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道3",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道4",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道101",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "3G-SDI",
                "dspStatus": "视频采集通道102",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI-I",
                "dspStatus": "视频采集通道103",
                "resolution": "NOSINGAL",
                "token": ""
            },
            {
                "videoType": "NOSINGAL",
                "videoInput": "DVI-I",
                "dspStatus": "视频采集通道104",
                "resolution": "NOSINGAL",
                "token": ""
            }
        ],
        "temperature": "0",
        "memoryUtilization": "7.49%",
        "humidity": "0",
        "deviceModel": "EN11_DE2",
        "hardwareVersion": "v3.0",
        "status.cpu": "40.73",
        "softwareVersion": "3.0.1.6",
        "machineType": "9",
        "status.cpu_1": "17.67"
    }
];